<template>
  <div>
    
    <div class="title">工程管理</div>
    <!-- 录入按钮 -->
    <div class="toadd">
      <div style="text-align: right"><el-button type="primary" @click="toAdd">录入</el-button></div>
    </div>

    <!-- 表格数据 -->
    <!-- 
    type="index" 显示该行的索引（从 1 开始计算）
    
     -->
    <div class="table">
      <el-table :data="engData" style="width: 100%">
        <el-table-column type="index" :index="1" label="序号" width="80">
        </el-table-column>
        <el-table-column prop="serial_number" label="编号" width="180">
        </el-table-column>
        <el-table-column prop="name" label="名称" width="380">
        </el-table-column>
        <el-table-column prop="type" label="工程类型"> </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template v-slot="scope">
            <div>
              <el-tag v-if="scope.row.status === '监测中'" type="success">
                监测中</el-tag>
              <el-tag v-else-if="scope.row.status === '未绑定'" type="warning">未绑定</el-tag>
              <el-tag v-else type="danger">已结束</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <!-- 作用域插槽 -->
          <template v-slot="scope">
            <div>
              <el-button type="text" @click="($event) => toEdit(scope.row)">修改</el-button>

              <el-button type="text" v-if="scope.row.status == '已结束'" disabled>绑定</el-button>
              <el-button type="text" @click="($event) => toDetails(scope.row)" v-if="
                  scope.row.status == '未绑定' || scope.row.status === '监测中'
                ">绑定</el-button>

              <el-button type="text" v-if="
                  scope.row.status === '已结束' || scope.row.status === '未绑定'
                " disabled>结束</el-button>

              <el-button type="text" v-if="scope.row.status === '监测中'"
                @click="($event) => toFinish(scope.row.id)">结束</el-button>

              <el-button type="text" v-if="scope.row.status === '未绑定'"
                @click="($event) => toDelete(scope.row.id)">删除</el-button>
              <el-button type="text" v-if="
                  scope.row.status === '监测中' || scope.row.status === '已结束'
                " disabled>删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页按钮 -->
    <div class="page" style="text-align: right; margin-top: 15px">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="params.page" :page-sizes="[2, 5, 10, 20]" :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" hide-on-single-page>
      </el-pagination>
    </div>

    <!-- 抽屉 -->
    <!-- 
      v-model 双向绑定
      :model v-model的缩写
      prop 父向子传值
      close 关闭抽屉事件做的事情
     -->
    <el-drawer @close="toClose" size="50%" :title="this.title" :visible.sync="dialog"
      direction="rtl" custom-class="demo-drawer" ref="drawer">
      <div class="demo-drawer__content">
        <el-form ref="myForm" :model="form" :rules="rules">
          <el-row>
            <el-col :span="12">
              <el-form-item prop="serial_number" label="编号" :label-width="formLabelWidth">
                <el-input v-model="form.serial_number" autocomplete="off"
                  placeholder="请输入工程编号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="name" label="名称" :label-width="formLabelWidth">
                <el-input v-model="form.name" autocomplete="off" placeholder="请输入工程名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="type" label="工程类型" :label-width="formLabelWidth">
                <el-select clearable v-model="form.type" placeholder="请选择工程类型">
                  <el-option label="园区" value="园区"></el-option>
                  <el-option label="写字楼" value="写字楼"></el-option>
                  <el-option label="建筑工地" value="建筑工地"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="charge_id" label="区域经理" :label-width="formLabelWidth">
                <el-select clearable v-model="form.charge_id" placeholder="请选择区域经理">
                  <el-option v-for="item in cData" :key="item.id" :label="item.realname"
                    :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="longitude" label="经度" :label-width="formLabelWidth">
                <el-input v-model="form.longitude" autocomplete="off"
                  placeholder="请输入经度"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="latitude" label="纬度" :label-width="formLabelWidth">
                <el-input v-model="form.latitude" autocomplete="off" placeholder="请输入维度"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="address1" label="地址" :label-width="formLabelWidth">
                <el-cascader v-model="form.address1" :props="{
                    value: 'name',
                    label: 'name',
                  }" :options="options" clearable></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="address2" label="详细地址" :label-width="formLabelWidth">
                <el-input v-model="form.address2" autocomplete="off"
                  placeholder="请输入详细地址"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="customer_name" label="客户姓名" :label-width="formLabelWidth">
                <el-input v-model="form.customer_name" autocomplete="off"
                  placeholder="请输入客户姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="customer_telephone" label="客户电话" :label-width="formLabelWidth">
                <el-input v-model="form.customer_telephone" autocomplete="off"
                  placeholder="请输入客户电话"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 不懂 -->
        <div class="demo-drawer__footer">
          <el-button @click="($event) => (dialog = false)">取 消</el-button>
          <el-button type="primary" @click="toSave">确定</el-button>
        </div>
      </div>
    </el-drawer>
    
  </div>
</template>

<script>
import { get, postJSON, del } from '@/utils/request'
import pca from '@/assets/pca.json'
export default {
    data() {
        return {
            //区域经理
            cData: [],
            //表单验证规则
            rules: {
                serial_number: [
                    { required: true, message: '请输入工程编号', trigger: 'blur' },
                    // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
                ],
                name: [{ required: true, message: '请输入工程名称', trigger: 'blur' }],
                type: [{ required: true, message: '请选择工程类型', trigger: 'change' }],
                charge_id: [{ required: true, message: '请选择区域经理', trigger: 'change' }],
                longitude: [{ required: true, message: '请输入经度', trigger: 'blur' }],
                latitude: [{ required: true, message: '请输入纬度', trigger: 'blur' }],
                address1: [{ required: true, message: '请选择地址', trigger: 'change' }],
                address2: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
                customer_name: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
                customer_telephone: [
                    { required: true, message: '请输入客户手机号', trigger: 'blur' },
                ],
            },
            //级联选择器配置项
            options: pca,
            //工程变量
            engData: [],
            //分页数据
            params: {
                page: 1,
                pageSize: 5,
            },
            //总条数
            total: 0,
            title: '',
            dialog: false,
            form: {},
            formLabelWidth: '80px',
        }
    },

    methods: {
        //结束工程
        toFinish(id) {
            // console.log(id);
            this.$confirm('此操作将结束该工程, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    //发送结束请求
                    let res = await get('/engineer/finish', { id }) //{id: id}的简写
                    this.$message({
                        type: 'success',
                        message: res.message,
                    })
                    //刷新页面
                    this.getEngData()
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除',
                    })
                })
        },
        //跳转到详情页面
        toDetails(row) {
            //路由跳转
            this.$router.push({
                path: '/am/engineer/Details',
                query: row,
            })
        },
        //去删除未绑定工程
        toDelete(id) {
            this.$confirm('此操作将删除该工程, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    //发送删除请求
                    let res = await del('/engineer/deleteById', { id }) //{id: id}的简写
                    this.$message({
                        type: 'success',
                        message: res.message,
                    })
                    //当删除的是本页面的最后一个数据时
                    if (this.total % this.params.pageSize == 1) {
                        if (this.params.page != 1) {
                            this.params.page--
                        }
                    }
                    //刷新页面
                    this.getEngData()
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除',
                    })
                })
        },

        //关闭抽屉
        toClose() {
            //重置表单校验
            this.$refs['myForm'].resetFields()
            this.dialog = false
        },

        //去修改
        toEdit(row) {
            // console.log(row, '--------');
            this.dialog = true
            this.title = '修改工程信息'
            this.form = { ...row }
        },

        //获取区域经理
        async getCData() {
            let res = await get('/user/pageQuery', {
                page: 1,
                pageSize: 1000,
                role_id: 3,
            })
            // console.log(res);
            this.cData = res.data.list
        },

        //去录入
        toAdd() {
            //打开抽屉
            this.dialog = true
            this.title = '录入工程信息'
            this.form = {}
        },

        //去提交
        toSave() {
            //refs----> {name:"zhangsan"}  refs.name 或 refs['name']
            this.$refs['myForm'].validate(async (valid) => {
                if (valid) {
                    // alert("submit!");
                    // console.log(this.form);
                    let obj = { ...this.form }
                    obj.address = obj.address1.join('') + obj.address2
                    // console.log(obj.address)
                    delete obj.address1
                    delete obj.address2
                    // console.log(obj);
                    let res = await postJSON('/engineer/saveOrUpdate', obj)
                    if (res.status === 200) {
                        this.$notify({
                            title: '成功',
                            message: '这是一条成功的提示消息',
                            type: 'success',
                        })
                        //清除表单校验
                        this.toClose()
                        //当新增到下一页面时
                        if (this.total % this.params.pageSize == 0) {
                            this.params.page++
                        }
                        //刷新页面
                        this.getEngData()
                    } else {
                        this.$notify({
                            title: '失败',
                            message: res.message,
                            type: 'error',
                        })
                    }
                    //关闭抽屉
                    this.dialog = false
                } else {
                    // console.log("error submit!!");
                    return false
                }
            })
        },

        //获取工程数据
        async getEngData() {
            let res = await get('/engineer/pageQuery', this.params)
            // console.log(res);
            this.engData = res.data.list
            this.total = res.data.total
        },

        //页码条数发生变化函数
        handleSizeChange(pageSize) {
            // console.log(pageSize, '条数');
            this.params.pageSize = pageSize
            //重新请求数据
            this.getEngData()
        },

        //页面发生变化函数
        handleCurrentChange(page) {
            // console.log(page, '页码');
            this.params.page = page
            this.getEngData()
        },
    },

    created() {
        this.getEngData()
        this.getCData()
    },
}
</script>

<style>
.title {
    width: 1288px;
    height: 42px;
    background-color: #f4f4f4;
    line-height: 42px;
    padding-left: 14px;
    border-left: 5px solid rgb(248, 128, 128);
}
</style>